package config

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var mongoClient *mongo.Client

// InitMongoDB 初始化 MongoDB 连接
func InitMongoDB(uri string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		return fmt.Errorf("failed to connect to MongoDB: %w", err)
	}

	// 测试连接
	err = client.Ping(ctx, nil)
	if err != nil {
		return fmt.Errorf("failed to ping MongoDB: %w", err)
	}

	mongoClient = client
	log.Println("Connected to MongoDB!")
	return nil
}

// GetMongoClient 获取 MongoDB 客户端
func GetMongoClient() *mongo.Client {
	return mongoClient
}

// GetDatabase 获取数据库
func GetDatabase(name string) *mongo.Database {
	return mongoClient.Database(name)
}

// CloseMongoDB 关闭 MongoDB 连接
func CloseMongoDB() error {
	if mongoClient == nil {
		return nil
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	return mongoClient.Disconnect(ctx)
}
